import axios from 'axios';
import { toast } from 'react-toastify';

interface IParams {
  path: string;
  args?: Record<string, unknown> | undefined;
  method?: 'post' | 'get' | 'put' | 'delete';
}

interface IReturnType {
  returnCode?: number;
  returnDesc?: string;
  data?: any;
}

const instance = axios.create();

export const doRequest = (params: IParams) => {
  const { path, args, method = 'get' } = params;
  if (!path) return;
  const config = {
    data: args,
    params: method === 'get' ? args : null,
    url: path,
    method,
    headers: { 'Content-Type': 'application/json' },
  };
  return instance.request(config).then((res) => {
    const { data: response }: { data: IReturnType } = res || {};
    if (response) {
      const { returnCode, data } = response;
      if (returnCode === 17000) {
        return data;
      } else {
        toast.error(response?.returnDesc || '请求失败');
        throw new Error(response?.returnDesc);
      }
    } else {
      throw new Error(res?.statusText);
    }
  });
};

export default doRequest;
